<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Testing websockets</title>
</head>
<body>
<div id="conn_div">

</div>
<textarea id="txt"></textarea>
<button type="button" onclick="send();">发送</button>

<div id="text">

</div>

<script src="http://cdn.bootcss.com/jquery/2.2.0/jquery.min.js"></script>
<script src="http://cdn.bootcss.com/json2/20150503/json2.min.js"></script>
<script type="text/javascript">
    $(function(){
        startConnect();
    })
    var WS;
    var startConnect = function(){
        WS =new WebSocket('ws://localhost/ws');
        WS.onerror = function(event) {
            onError(event)
        };

        WS.onopen = function(event) {
            onOpen(event)
        };

        WS.onmessage = function(event) {
            onMessage(event)
        };
    }


    function onMessage(event) {
        console.log(event);
        var resp = JSON.parse(event.data);
        console.log(resp);
        $("#text").append('<p>用户'+resp.id+'：'+resp.msg+'</p>');
    }

    function onOpen(event) {
        console.log(event);
        console.log("开始连接..");
        $("#conn_div").html('<span style="background-color: green;">连接成功</span>');
    }

    function onError(event) {
        console.error(event.data);
    }

    function send() {
        var text = $("#txt").val();
        WS.send(text);
    }
</script>
</body>
</html>